package cn.buk.tms.message;

import cn.buk.qms.service.EnterpriseService;
import cn.buk.tms.common.dto.CommonMessageDto;
import cn.buk.tms.common.dto.FlightSearchStatDto;
import cn.buk.common.util.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * @author yfdai
 * @date 16/6/2
 * jms-eotms 表示接收来自eotms发送的消息
 */
@Profile({"jms-eotms"})
@Component
public class AlertHandler {

  private static final Logger logger = LogManager.getLogger(AlertHandler.class);

  private final EnterpriseService enterpriseService;

  @Autowired
  public AlertHandler(EnterpriseService enterpriseService) {
      this.enterpriseService = enterpriseService;
  }

  @JmsListener(destination = "eotms.queue.statics")
  public void receiveMessage(final Message<String> message) {

    logger.info(message.getPayload());

    CommonMessageDto<FlightSearchStatDto> messageDto =
            JSON.parseObject(message.getPayload(), new TypeReference<>() {
            });

    final int year = DateUtil.getYear(DateUtil.getCurDate());
    final int month = DateUtil.getMonth(DateUtil.getCurDate());

    logger.info(messageDto.getList().size() + ", " + year + ", " + month);

    for (FlightSearchStatDto dto : messageDto.getList()) {
      //查看是否本月的统计
      if (dto.getYear() != year || dto.getMonth() != month) {
        continue;
      }

      enterpriseService.updateFlightSearchStat(dto);
    }
  }
}
